package com.example.blog_spring.controller;

import com.example.blog_spring.constant.Constants;
import com.example.blog_spring.model.BlogInfo;
import com.example.blog_spring.model.Result;
import com.example.blog_spring.model.UserInfo;
import com.example.blog_spring.service.BlogService;
import com.example.blog_spring.service.UserService;
import com.example.blog_spring.utils.JwtUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private BlogService blogService;

    @RequestMapping("/login")
    public Result<String> login(String userName, String password, HttpSession session){
        return userService.login(userName, password, session);
    }

    @RequestMapping("/register")
    public Result<String> register(String userName, String password, String confirmPassword, String githubAddress){
        return userService.register(userName, password, confirmPassword, githubAddress);
    }
    @RequestMapping("/getLoginUserInfo")
    public UserInfo getLoginUserInfo(HttpServletRequest request){
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        Integer id = JwtUtils.getIdByToken(token);
        log.info("根据id, {} 获取用户信息", id);
        if(id == null){
            return null;
        }
        return userService.selectById(id);
    }

    @RequestMapping("/getAuthorInfo")
    public UserInfo getAuthorInfo(Integer blogId){
        if(blogId <= 0){
            return null;
        }
        BlogInfo blogInfo = blogService.getBlogDetailById(blogId);
        if(blogInfo == null || blogInfo.getUserId() <= 0){
            log.error("博客信息不存在或作者信息不合法, blogId: {}", blogId);
            return null;
        }
        return userService.selectById(blogInfo.getUserId());
    }

    @ResponseBody
    @RequestMapping("/updateUserInfo")
    public Result<String> updateUserInfo(@RequestParam(value = "myimg") MultipartFile file,
                                         HttpServletRequest request) {
        // 保存数据库的路径
        String sqlPath = null;
        // 定义文件保存的本地路径
        String localPath = null;
        // 定义 文件名
        String filename = null;
        if (!file.isEmpty()) {
            //生成uuid作为文件名称
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            File filePath = new File("D:\\tmp\\photo\\");
            if (!filePath.exists()) {
                filePath.mkdirs();
            }
            // 获得文件类型（可以判断如果不是图片，禁止上传）
            String contentType = file.getContentType();
            // 获得文件后缀名
            String suffixName = contentType.substring(contentType.indexOf("/") + 1);
            // 得到 文件名
            filename = uuid + "." + suffixName;
            // 文件保存路径
            try {
                file.transferTo(new File(filePath+"\\"+ filename));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        // 把图片的相对路径保存至数据库
        sqlPath = filename;
        UserInfo userInfo = new UserInfo();
        String token = request.getHeader(Constants.REQUEST_HEADER_TOKEN);
        Integer id = JwtUtils.getIdByToken(token);
        userInfo.setId(id);
        userInfo.setPhoto(sqlPath);
        try {
            Integer result = userService.updateUserInfo(userInfo);
            if(result == 1){
                return Result.success("修改成功");
            }
        } catch (Exception e){
            e.printStackTrace();
        }
        return Result.fail("修改失败");
    }
}
